import { createRouter, createWebHistory } from "vue-router";
import { useUserStore } from "@/stores/user";
import userRoutes from "./modules/user";
import merchantRoutes from "./modules/merchant";
import hotelAdminRoutes from "./modules/hotelAdmin";
import adminRoutes from "./modules/admin";
import { ElMessage } from "element-plus";
import ArticlesView from "@/views/community/articles/index.vue";

const routes = [
  {
    path: "/",
    name: "Home",
    component: () => import("@/views/home/index.vue"),
    meta: {
      layout: "default",
      title: "首页",
    },
  },
  {
    path: "/spots",
    name: "Spots",
    component: () => import("@/views/spots/index.vue"),
    meta: {
      title: "景点",
    },
  },
  {
    path: "/spots/:id",
    name: "SpotDetail",
    component: () => import("@/views/spots/detail.vue"),
    meta: {
      title: "景点详情",
    },
  },
  {
    path: "/spots-overview",
    name: "SpotsOverview",
    component: () => import("@/views/spots-overview/index.vue"),
    meta: {
      title: "景点总览",
    },
  },
  {
    path: "/tour-guide",
    name: "TourGuide",
    component: () => import("@/views/tour-guide/index.vue"),
    meta: {
      title: "导游服务",
    },
  },
  {
    path: "/tour-guide/:id",
    name: "TourGuideDetail",
    component: () => import("@/views/tour-guide/detail.vue"),
    meta: {
      title: "导游详情",
    },
  },
  {
    path: "/ai-chat",
    name: "AIChat",
    component: () => import("@/views/ai-chat/index.vue"),
    meta: {
      title: "智能助手",
    },
  },
  {
    path: "/shop",
    name: "Shop",
    component: () => import("@/views/shop/index.vue"),
    meta: {
      title: "文创商城",
    },
  },
  {
    path: "/shop/product/:id",
    name: "ProductDetail",
    component: () => import("@/views/shop/ProductDetail.vue"),
    meta: {
      title: "商品详情",
    },
  },
  {
    path: "/shop/store/:id",
    name: "StoreDetail",
    component: () => import("@/views/shop/StoreDetail.vue"),
    meta: {
      title: "店铺详情",
    },
  },
  {
    path: "/community",
    name: "Community",
    component: () => import("@/views/community/index.vue"),
    meta: {
      title: "社区",
    },
  },
  {
    path: "/community/articles",
    name: "Articles",
    component: ArticlesView,
    meta: {
      title: "文章列表",
    },
  },
  {
    path: "/community-articles",
    name: "ArticlesAlternative",
    component: ArticlesView,
    meta: {
      title: "文章列表",
    },
  },
  {
    path: "/community/topic/:id",
    name: "TopicDetail",
    component: () => import("@/views/community/topic/index.vue"),
    meta: {
      title: "话题详情",
    },
  },
  {
    path: "/community/article/:id",
    name: "ArticleDetail",
    component: () => import("@/views/community/article/index.vue"),
    meta: {
      title: "文章详情",
    },
  },
  {
    path: "/community/event/:id",
    name: "EventDetail",
    component: () => import("@/views/community/event/index.vue"),
    meta: {
      title: "活动详情",
    },
  },
  {
    path: "/guides",
    name: "TravelGuides",
    component: () => import("@/views/guides/index.vue"),
    meta: {
      title: "旅游攻略",
    },
  },
  {
    path: "/guides/:id",
    name: "TravelGuideDetail",
    component: () => import("@/views/guides/detail.vue"),
    meta: {
      title: "攻略详情",
    },
  },
  {
    path: "/ai-guide",
    name: "AIGuide",
    component: () => import("@/views/guides/ai.vue"),
    meta: {
      title: "智能攻略",
    },
  },
  {
    path: "/ai-guide/result",
    name: "AIGuideResult",
    component: () => import("@/views/guides/result.vue"),
    meta: {
      title: "攻略生成结果",
    },
  },
  {
    path: "/map",
    name: "Map",
    component: () => import("@/views/map/index.vue"),
    meta: {
      title: "地图导览",
    },
  },
  {
    path: "/service",
    name: "Service",
    component: () => import("@/views/service/index.vue"),
    meta: {
      title: "便民服务",
    },
  },
  {
    path: "/search",
    name: "Search",
    component: () => import("@/views/search/index.vue"),
    meta: {
      title: "搜索结果",
    },
  },
  userRoutes,
  merchantRoutes,
  hotelAdminRoutes,
  adminRoutes,
  {
    path: "/order/confirm",
    name: "OrderConfirm",
    component: () => import("@/views/order/confirm.vue"),
    meta: {
      requiresAuth: true,
      title: "确认订单",
    },
  },
  {
    path: "/order/payment",
    name: "OrderPayment",
    component: () => import("@/views/order/payment.vue"),
    meta: {
      requiresAuth: true,
      title: "订单支付",
    },
  },
  {
    path: "/order/list",
    name: "OrderList",
    component: () => import("@/views/order/list.vue"),
    meta: {
      requiresAuth: true,
      title: "订单列表",
    },
  },
  {
    path: "/order/detail/:id",
    name: "OrderDetail",
    component: () => import("@/views/order/detail.vue"),
    meta: {
      requiresAuth: true,
      title: "订单详情",
    },
  },
  {
    path: "/order/:id",
    name: "OrderDetail",
    component: () => import("@/views/order/detail.vue"),
    meta: {
      requiresAuth: true,
      title: "订单详情",
    },
  },
  {
    path: "/order/:id/logistics",
    name: "OrderLogistics",
    component: () => import("@/views/order/logistics.vue"),
    meta: {
      requiresAuth: true,
      title: "物流信息",
    },
  },
  {
    path: "/order/review",
    name: "OrderReview",
    component: () => import("@/views/order/review.vue"),
    meta: {
      requiresAuth: true,
      title: "订单评价",
    },
  },
  {
    path: "/order/result",
    name: "OrderResult",
    component: () => import("@/views/order/detail.vue"),
    meta: {
      requiresAuth: true,
      title: "下单结果",
    },
    beforeEnter: (to, from, next) => {
      const type = to.query.type || "product";
      const orderId = to.query.orderId;
      if (type === "hotel") {
        next({
          name: "HotelOrderDetail",
          params: { id: orderId },
          query: { status: to.query.status },
        });
      } else if (type === "ticket") {
        next({
          name: "TicketOrderDetail",
          params: { id: orderId },
          query: { status: to.query.status },
        });
      } else if (type === "experience") {
        next({
          name: "ExperienceOrderDetail",
          params: { id: orderId },
          query: { status: to.query.status },
        });
      } else if (type === "guide") {
        next({
          name: "GuideOrderDetail",
          params: { id: orderId },
          query: { status: to.query.status },
        });
      } else {
        next();
      }
    },
  },
  {
    path: "/order/hotel/:id",
    name: "HotelOrderDetail",
    component: () => import("@/views/order/hotel-detail.vue"),
    meta: {
      requiresAuth: true,
      title: "酒店订单详情",
    },
  },
  {
    path: "/order/ticket/:id",
    name: "TicketOrderDetail",
    component: () => import("@/views/order/ticket-detail.vue"),
    meta: {
      requiresAuth: true,
      title: "门票订单详情",
    },
  },
  {
    path: "/order/experience/:id",
    name: "ExperienceOrderDetail",
    component: () => import("@/views/order/experience-detail.vue"),
    meta: {
      requiresAuth: true,
      title: "体验订单详情",
    },
  },
  {
    path: "/order/guide/:id",
    name: "GuideOrderDetail",
    component: () => import("@/views/order/guide-detail.vue"),
    meta: {
      requiresAuth: true,
      title: "导游订单详情",
    },
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/auth/login.vue"),
    meta: {
      title: "登录",
      requiresAuth: false,
    },
  },
  {
    path: "/register",
    name: "Register",
    component: () => import("@/views/auth/register.vue"),
    meta: {
      title: "注册",
      requiresAuth: false,
    },
  },
  {
    path: "/forgot-password",
    name: "ForgotPassword",
    component: () => import("@/views/auth/forgot-password.vue"),
    meta: {
      title: "找回密码",
      requiresAuth: false,
    },
  },
  {
    path: "/privacy",
    name: "Privacy",
    component: () => import("@/views/other/privacy.vue"),
    meta: {
      title: "隐私政策",
    },
  },
  {
    path: "/terms",
    name: "Terms",
    component: () => import("@/views/other/terms.vue"),
    meta: {
      title: "用户协议",
    },
  },
  {
    path: "/about",
    name: "About",
    component: () => import("@/views/about/index.vue"),
    meta: {
      title: "关于我们",
    },
  },
  {
    path: "/merchant/apply",
    name: "MerchantApply",
    component: () => import("@/views/merchantapply/index.vue"),
    meta: {
      layout: "default",
      title: "商家入驻",
    },
  },
  {
    path: "/merchant/apply-form",
    name: "MerchantApplyForm",
    component: () => import("@/views/merchantapply/form.vue"),
    meta: {
      layout: "default",
      title: "入驻申请",
    },
  },
  {
    path: "/help",
    name: "Help",
    component: () => import("@/views/help/index.vue"),
    meta: {
      title: "帮助中心",
      requiresAuth: false,
    },
  },
  {
    path: "/help/guide",
    name: "HelpGuide",
    component: () => import("@/views/help/guide.vue"),
    meta: {
      title: "使用指南",
      requiresAuth: false,
    },
  },
  {
    path: "/audio-guide",
    name: "AudioGuide",
    component: () => import("@/views/audio-guide/index.vue"),
    meta: {
      title: "语音导览",
    },
  },
  {
    path: "/events",
    name: "Events",
    component: () => import("@/views/events/index.vue"),
    meta: {
      title: "活动日历",
      requiresAuth: false,
    },
  },
  {
    path: "/parking",
    name: "Parking",
    component: () => import("@/views/parking/index.vue"),
    meta: {
      title: "停车信息",
    },
  },
  {
    path: "/news",
    name: "News",
    component: () => import("@/views/news/index.vue"),
    meta: {
      title: "新闻资讯",
    },
  },
  {
    path: "/news/:id",
    name: "NewsDetail",
    component: () => import("@/views/news/detail.vue"),
    meta: {
      title: "资讯详情",
    },
  },
  {
    path: "/experiences",
    name: "Experiences",
    component: () => import("@/views/experiences/index.vue"),
    meta: {
      title: "文化体验",
    },
  },
  {
    path: "/experiences/:id",
    name: "ExperienceDetail",
    component: () => import("@/views/experiences/detail.vue"),
    meta: {
      title: "体验详情",
    },
  },
  {
    path: "/photography",
    name: "Photography",
    component: () => import("@/views/photography/index.vue"),
    meta: {
      title: "摄影打卡",
      requiresAuth: false,
    },
  },
  {
    path: "/photography/:id",
    name: "PhotographyDetail",
    component: () => import("@/views/photography/detail.vue"),
    meta: {
      title: "打卡地详情",
      requiresAuth: false,
    },
  },
  {
    path: "/photography/works/:id",
    name: "PhotographyWorkDetail",
    component: () => import("@/views/photography/works/[id].vue"),
    meta: {
      title: "摄影作品详情",
      requiresAuth: false,
    },
  },
  {
    path: "/user/profile/:id",
    name: "UserProfileVisitor",
    component: () => import("@/views/user/profile/[id].vue"),
    meta: {
      title: "用户主页",
      requiresAuth: false,
    },
  },
  {
    path: "/merchant/status",
    name: "MerchantStatus",
    component: () => import("@/views/merchantapply/status.vue"),
    meta: {
      title: "入驻审核状态",
    },
  },
  {
    path: "/hotel",
    name: "Hotel",
    component: () => import("@/views/hotel/index.vue"),
    meta: {
      title: "酒店住宿",
    },
  },
  {
    path: "/hotel/:id",
    name: "HotelDetail",
    component: () => import("@/views/hotel/detail.vue"),
    meta: {
      title: "酒店详情",
    },
  },
  {
    path: "/download",
    children: [
      {
        path: "app",
        name: "AppDownload",
        component: () => import("@/views/download/app.vue"),
        meta: {
          title: "APP下载",
        },
      },
      {
        path: "desktop",
        name: "DesktopDownload",
        component: () => import("@/views/download/desktop.vue"),
        meta: {
          title: "桌面端下载",
        },
      },
    ],
  },
  {
    path: "/feedback",
    name: "Feedback",
    component: () => import("@/views/feedback/index.vue"),
    meta: {
      title: "意见反馈",
    },
  },
  {
    path: "/food",
    name: "Food",
    component: () => import("@/views/food/index.vue"),
    meta: {
      title: "特色美食",
      requiresAuth: false,
    },
  },
  {
    path: "/food/:id",
    name: "FoodDetail",
    component: () => import("@/views/food/detail.vue"),
    meta: {
      title: "美食详情",
      requiresAuth: false,
    },
  },
  {
    path: "/:pathMatch(.*)*",
    name: "NotFound",
    component: () => import("@/views/error/404.vue"),
    meta: {
      title: "页面未找到",
    },
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  },
});

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();

  // 检查是否需要登录
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    next({
      name: "Login",
      query: { redirect: to.fullPath },
    });
    return;
  }

  // 检查是否需要商家权限
  if (to.meta.requiresMerchant) {
    if (!userStore.isLoggedIn) {
      next({
        name: "Login",
        query: { redirect: to.fullPath },
      });
      return;
    }
    if (userStore.userType !== "merchant") {
      next({
        name: "MerchantApply",
      });
      return;
    }
  }

  // 检查酒店商家权限
  if (to.meta.requiresHotelMerchant) {
    if (!userStore.isLoggedIn) {
      next({
        name: "Login",
        query: { redirect: to.fullPath },
      });
      return;
    }
    if (!userStore.isHotelMerchant) {
      ElMessage.error("该页面仅限酒店商家访问");
      next("/");
      return;
    }
  }

  // 检查文创商家权限
  if (to.meta.requiresCulturalMerchant) {
    if (!userStore.isLoggedIn) {
      next({
        name: "Login",
        query: { redirect: to.fullPath },
      });
      return;
    }
    if (!userStore.isCulturalMerchant) {
      ElMessage.error("该页面仅限文创商家访问");
      next("/");
      return;
    }
  }

  // 检查是否需要管理员权限
  if (to.meta.requiresAdmin) {
    if (!userStore.isLoggedIn) {
      next({
        name: "Login",
        query: { redirect: to.fullPath },
      });
      return;
    }
    if (!userStore.isAdmin) {
      ElMessage.error("该页面仅限系统管理员访问");
      next("/");
      return;
    }
  }

  next();
});

// 添加全局后置钩子
router.afterEach((to, from) => {
  // 设置页面标题
  const title = to.meta.title || to.name || "贵港文旅+";
  document.title = `${title} - 贵港文旅+`;

  // 确保滚动到顶部
  window.scrollTo({
    top: 0,
    behavior: "smooth",
  });
});

export default router;
